package com.grao.waterschool.human.manager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grao.waterschool.human.common.R;
import com.grao.waterschool.human.entiry.po.OdsPksj;
import com.grao.waterschool.human.entiry.po.TWschoolCourseInfo;
import com.grao.waterschool.human.entiry.vo.CourseListInfo;
import com.grao.waterschool.human.entiry.vo.JsVo;
import com.grao.waterschool.human.entiry.vo.KcVo;
import com.grao.waterschool.human.entiry.vo.SelectCourseCriteria;
import com.grao.waterschool.human.manager.service.CourseService;
import com.grao.waterschool.human.mapper.OdsPksjMapper;
import com.grao.waterschool.human.mapper.TWschoolCourseInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseServiceImpl implements CourseService {

    private final RestTemplate restTemplate;


    @Autowired
    private OdsPksjMapper odsPksjMapper;

    private final SymmetricCrypto aes;


    int totalNum = 100000;

    private final String DATA = "20240825";
    //    private static final String COURSE_LIST_URL = "http://10.0.25.125:9000/prod-api4/api/web/query/out/0yELPDuO/college/educat/lesson";
    private static final String COURSE_LIST_URL = "http://10.0.25.125:9000/prod-api4/api/web/query/out/0yELPDuO/college/educat/lessoncourse_activity";
    private static final String APP_KEY = "NbxYWFuT";
    private static final String APP_SECRET = "65cd5791d3dc362e7b9593e061867ea6";
    private static final int PAGE_SIZE = 1000;
    private static final int THREAD_POOL_SIZE = 4;

    public CourseServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
//        this.odsPksjMapper = odsPksjMapper;
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), APP_SECRET.getBytes(StandardCharsets.UTF_8)).getEncoded();
        this.aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
    }

    @Override
    public R<String> getCourseList() {

        AtomicReference<R<String>> courseListMethod = new AtomicReference<>(R.success("数据获取成功"));

        // 初始的总记录数
        int totalRecords = getTotalRecords(); // 假设这是获取总记录数的方法
        int totalPages = (totalRecords + PAGE_SIZE - 1) / PAGE_SIZE;

        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        for (int page = 1; page <= totalPages; page++) {
            int finalPage = page;
            executorService.submit(() -> {
                R<String> result = getCourseListMethod(finalPage);
                if (result.getStatus() == 0) {
                    courseListMethod.set(result);
                }
            });
        }

        executorService.shutdown();
        try {
            // 等待所有任务完成
            if (!executorService.awaitTermination(1, TimeUnit.HOURS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }

        if (courseListMethod.get().getStatus() == 0) {
            return R.success("数据更新成功");
        } else {
            return R.error("数据更新失败");
        }
    }

    // 假设这是一个获取总记录数的方法
    private int getTotalRecords() {
        // 这里只是一个示例值
        return totalNum;
    }

    private R<String> getCourseListMethod(int page) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("page", String.valueOf(page));
        jsonObject.putOpt("size", String.valueOf(PAGE_SIZE));
        JSONObject encryptedParams = encryptParams(jsonObject);
        R<String> stringR = postMethodTest(COURSE_LIST_URL, encryptedParams);
        if (stringR.getStatus() == 0) {
            log.info("数据插入成功");
            return R.success("数据插入成功");
        } else {
            return R.success("数据插入失败");
        }
    }

    private JSONObject encryptParams(JSONObject jsonObject) {
        String encryptHex = aes.encryptHex(jsonObject.toString());
        JSONObject requestParam = new JSONObject();
        requestParam.putOpt("appKey", APP_KEY);
        requestParam.putOpt("queryEncryptionStr", encryptHex);
        log.info("请求参数 {}", requestParam);
        return requestParam;
    }

    private R<String> postMethod(String url, JSONObject params) {
        log.info("请求地址:{}", url);
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, params, String.class);
            log.info("返回数据：{}", responseEntity);
            if (responseEntity.getBody() == null) {
                log.error("响应体为空");
                return R.error("数据响应体为空，请联系开发人员");
            }

            JSONObject result = JSONUtil.parseObj(responseEntity.getBody());
            String returnCode = result.getStr("returnCode");

            if (StringUtils.isNotEmpty(returnCode) && "200".equals(returnCode)) {
                JSONObject returnData = result.getJSONObject("returnData");
                JSONArray courseList = returnData.getJSONArray("list");
                if (courseList == null || courseList.isEmpty()) {
                    log.warn("课程列表数据为空");
                    return R.error("课程数据为空");
                }

                List<OdsPksj> courses = convertJsonArrayToOdsPksjList(courseList);

                // 过滤掉 SKSJ 小于 "20240825" 的课程
                DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

                // 过滤列表中的课程
                List<OdsPksj> filteredCourses = courses.stream()
                        .filter(course -> {
                            // 将 course.getGxsj() 从字符串解析为 LocalDateTime 对象
                            LocalDateTime gxsj = LocalDateTime.parse(course.getSjcjsj(), inputFormatter);

                            // 将 LocalDateTime 格式化为 yyyyMMdd 格式的字符串
                            String formattedGxsj = gxsj.format(outputFormatter);

                            // 将 formattedGxsj 与 DATA 进行字符串比较
                            return formattedGxsj.compareTo(DATA) >= 0;
                        })
                        .collect(Collectors.toList());

                insertCoursesInBatches(filteredCourses);

            } else {
                log.error("返回代码不为200，实际返回代码: {}", returnCode);
            }
        } catch (Exception e) {
            log.error("调用异常:", e);
        }
        log.info("数据插入成功");
        return R.success("数据插入成功");
    }

    private R<String> postMethodTest(String url, JSONObject params) {
        log.info("请求地址:{}", url);
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, params, String.class);
            log.info("返回数据：{}", responseEntity);
            if (responseEntity.getBody() == null) {
                log.error("响应体为空");
                return R.error("数据响应体为空，请联系开发人员");
            }
            log.info("返回数据：{}", responseEntity);
            JSONObject result = JSONUtil.parseObj(responseEntity.getBody());
            String returnCode = result.getStr("returnCode");

            if (StringUtils.isNotEmpty(returnCode) && "200".equals(returnCode)) {
                JSONObject returnData = result.getJSONObject("returnData");
                JSONArray courseList = returnData.getJSONArray("list");
                if (courseList == null || courseList.isEmpty()) {
                    log.warn("课程列表数据为空");
                    return R.error("课程数据为空");
                }

            } else {
                log.error("返回代码不为200，实际返回代码: {}", returnCode);
            }
        } catch (Exception e) {
            log.error("调用异常:", e);
        }
        log.info("数据插入成功");
        return R.success("数据插入成功");
    }


    @Transactional
    public void insertCoursesInBatches(List<OdsPksj> courses) {
        final int batchSize = 500;
        for (int i = 0; i < courses.size(); i += batchSize) {
            int end = Math.min(i + batchSize, courses.size());
            List<OdsPksj> batchList = courses.subList(i, end);
            odsPksjMapper.insert(batchList);
        }
    }

    public static List<OdsPksj> convertJsonArrayToOdsPksjList(JSONArray jsonArray) {
        return jsonArray.stream()
                .map(json -> JSON.parseObject(json.toString(), OdsPksj.class))
                .collect(Collectors.toList());
    }

    //查询课程列表
    @Override
    public Page<CourseListInfo> selectCourseList(SelectCourseCriteria selectCourseCriteria) {
        log.info("看来条件是空啊");
        if (ObjectUtil.isNull(selectCourseCriteria)) {
            selectCourseCriteria = new SelectCourseCriteria();
            selectCourseCriteria.setCurrentPage(1);
            selectCourseCriteria.setPageSize(10);
        } else {
            if (ObjectUtil.isNull(selectCourseCriteria.getCurrentPage()) || ObjectUtil.isNull(selectCourseCriteria.getPageSize())) {
                selectCourseCriteria.setCurrentPage(1);
                selectCourseCriteria.setPageSize(10);
            }
        }
        Page<CourseListInfo> page = new Page<>(selectCourseCriteria.getCurrentPage(), selectCourseCriteria.getPageSize());
        Integer start = (selectCourseCriteria.getCurrentPage() - 1) * selectCourseCriteria.getPageSize();
        selectCourseCriteria.setCurrentPage(start);
        List<CourseListInfo> courseListInfoList = odsPksjMapper.selectCourseList(selectCourseCriteria);
        QueryWrapper<OdsPksj> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(selectCourseCriteria.getJSH())) queryWrapper.eq("JSH", selectCourseCriteria.getJSH());
        if (ObjectUtil.isNotEmpty(selectCourseCriteria.getZC())) queryWrapper.eq("ZC", selectCourseCriteria.getZC());
        if (ObjectUtil.isNotEmpty(selectCourseCriteria.getJGH())) queryWrapper.eq("JGH", selectCourseCriteria.getJGH());
        if (ObjectUtil.isNotEmpty(selectCourseCriteria.getXQJ())) queryWrapper.eq("XQJ", selectCourseCriteria.getXQJ());
        if (ObjectUtil.isNotEmpty(selectCourseCriteria.getZYSSYXBMC())) queryWrapper.eq("ZYSSYXBMC", selectCourseCriteria.getZYSSYXBMC());
        Long totalCount = odsPksjMapper.selectCount(queryWrapper);
        page.setRecords(courseListInfoList);
        page.setTotal(totalCount);
        return page;
    }

    @Override
    public R<String> truncateTable() {

        // 清空表
        odsPksjMapper.truncateTable();

        // 循环检查表是否为空
        while (!isTableEmpty()) {
            try {
                // 等待 200 ms 后再次检查
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("等待表为空时中断", e);
            }
        }

        // 表为空后，继续下一步操作

        R<String> courseList = getCourseList();
        if (courseList.getStatus() == 0) {
            return R.success("数据更新成功");
        } else {
            return R.error("数据更新失败");
        }
    }

    @Override
    public List<String> selectZCList() {
        return odsPksjMapper.getZCList();
    }

    @Override
    public List<String> selectJSHList() {
        return odsPksjMapper.getJSHList();
    }

    @Override
    public List<JsVo> selectJGHList() {
        return odsPksjMapper.getJGHList();
    }

    @Override
    public List<KcVo> selectKCHList() {
        return odsPksjMapper.getKCHList();
    }

    @Override
    public List<String> getYxList() {
        return odsPksjMapper.getYxList();
    }

    @Override
    public List<OdsPksj> getList() {
        return odsPksjMapper.selectList(null);
    }

    @Override
    public void update(List<OdsPksj> odsPksjsList) {
        odsPksjMapper.updateById(odsPksjsList);
    }

    private boolean isTableEmpty() {
        int rowCount = odsPksjMapper.checkTableIsEmpty();
        return rowCount == 0;
    }

}
//        private R<String> postMethod(String url, JSONObject params) {
//        log.info("请求地址:{}", url);
//        try {
//            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, params, String.class);
//
//            if (responseEntity.getBody() == null) {
//                log.error("响应体为空");
//                return R.error("数据响应体为空，请联系开发人员");
//            }
//
//            JSONObject result = JSONUtil.parseObj(responseEntity.getBody());
//
//            String returnCode = result.getStr("returnCode");
//
//            if (StringUtils.isNotEmpty(returnCode) && "200".equals(returnCode)) {
//                JSONObject returnData = result.getJSONObject("returnData");
//                JSONArray courseList = returnData.getJSONArray("list");
//                if (courseList == null || courseList.isEmpty()) {
//                    log.warn("课程列表数据为空");
//
//                }
//                List<OdsPksj> courses = convertJsonArrayToOdsPksjList(courseList);
//                insertCoursesInBatches(courses);
//
//            } else {
//                log.error("返回代码不为200，实际返回代码: {}", returnCode);
//            }
//        } catch (Exception e) {
//            log.error("调用异常:", e);
//        }
//        log.info("数据插入成功");
//        return R.success("数据插入成功");
//    }
